<template>
  <div class="error-page">
    <div class="error-container">
      <div class="error-icon">
        <el-icon v-if="type === 'network'"><WifiOff /></el-icon>
        <el-icon v-else-if="type === 'server'"><Warning /></el-icon>
        <el-icon v-else-if="type === '404'"><QuestionFilled /></el-icon>
        <el-icon v-else><CircleCloseFilled /></el-icon>
      </div>
      
      <div class="error-content">
        <h2 class="error-title">{{ title }}</h2>
        <p class="error-description">{{ description }}</p>
        
        <div v-if="type === 'network'" class="network-status">
          <div class="status-item">
            <span class="status-label">网络状态：</span>
            <span :class="['status-value', networkStatus.online ? 'online' : 'offline']">
              {{ networkStatus.online ? '已连接' : '已断开' }}
            </span>
          </div>
          <div class="status-item">
            <span class="status-label">连接类型：</span>
            <span class="status-value">{{ networkStatus.type }}</span>
          </div>
          <div v-if="!networkStatus.online" class="status-item">
            <span class="status-label">重连倒计时：</span>
            <span class="status-value">{{ retryCountdown }}秒</span>
          </div>
        </div>
        
        <div class="error-actions">
          <el-button 
            type="primary" 
            @click="handleRetry"
            :loading="retrying"
            size="large"
          >
            {{ retrying ? '重试中...' : '重试' }}
          </el-button>
          <el-button 
            @click="handleGoHome"
            size="large"
          >
            返回首页
          </el-button>
          <el-button 
            v-if="showRefresh"
            @click="handleRefresh"
            size="large"
          >
            刷新页面
          </el-button>
        </div>
        
        <div v-if="showDetails" class="error-details">
          <el-collapse>
            <el-collapse-item title="错误详情" name="details">
              <div class="details-content">
                <div class="detail-item">
                  <span class="detail-label">错误代码：</span>
                  <span class="detail-value">{{ errorCode }}</span>
                </div>
                <div class="detail-item">
                  <span class="detail-label">错误时间：</span>
                  <span class="detail-value">{{ errorTime }}</span>
                </div>
                <div v-if="errorMessage" class="detail-item">
                  <span class="detail-label">错误信息：</span>
                  <span class="detail-value">{{ errorMessage }}</span>
                </div>
                <div v-if="requestUrl" class="detail-item">
                  <span class="detail-label">请求地址：</span>
                  <span class="detail-value">{{ requestUrl }}</span>
                </div>
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { 
  WifiOff, 
  Warning, 
  QuestionFilled, 
  CircleCloseFilled 
} from '@element-plus/icons-vue'

const props = defineProps({
  type: {
    type: String,
    default: 'error', // network, server, 404, error
    validator: (value) => ['network', 'server', '404', 'error'].includes(value)
  },
  title: {
    type: String,
    default: ''
  },
  description: {
    type: String,
    default: ''
  },
  errorCode: {
    type: [String, Number],
    default: ''
  },
  errorMessage: {
    type: String,
    default: ''
  },
  requestUrl: {
    type: String,
    default: ''
  },
  showDetails: {
    type: Boolean,
    default: false
  },
  showRefresh: {
    type: Boolean,
    default: true
  },
  autoRetry: {
    type: Boolean,
    default: false
  },
  retryInterval: {
    type: Number,
    default: 30
  }
})

const emit = defineEmits(['retry', 'goHome'])

const router = useRouter()
const retrying = ref(false)
const retryCountdown = ref(0)
let retryTimer = null

// 网络状态
const networkStatus = reactive({
  online: navigator.onLine,
  type: getConnectionType()
})

// 计算属性
const computedTitle = computed(() => {
  if (props.title) return props.title
  
  const titles = {
    network: '网络连接异常',
    server: '服务器错误',
    404: '页面不存在',
    error: '系统错误'
  }
  return titles[props.type] || '未知错误'
})

const computedDescription = computed(() => {
  if (props.description) return props.description
  
  const descriptions = {
    network: '请检查您的网络连接，我们将自动为您重试',
    server: '服务器暂时无法响应，请稍后重试',
    404: '您访问的页面不存在或已被删除',
    error: '系统出现了一些问题，请稍后重试'
  }
  return descriptions[props.type] || '发生了未知错误'
})

const errorTime = computed(() => {
  return new Date().toLocaleString()
})

// 获取连接类型
function getConnectionType() {
  const connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection
  if (connection) {
    return connection.effectiveType || connection.type || '未知'
  }
  return '未知'
}

// 网络状态监听
const handleOnline = () => {
  networkStatus.online = true
  networkStatus.type = getConnectionType()
  if (props.type === 'network' && props.autoRetry) {
    handleRetry()
  }
}

const handleOffline = () => {
  networkStatus.online = false
  if (props.type === 'network' && props.autoRetry) {
    startRetryCountdown()
  }
}

// 开始重试倒计时
const startRetryCountdown = () => {
  retryCountdown.value = props.retryInterval
  retryTimer = setInterval(() => {
    retryCountdown.value--
    if (retryCountdown.value <= 0) {
      clearInterval(retryTimer)
      if (networkStatus.online) {
        handleRetry()
      } else {
        startRetryCountdown()
      }
    }
  }, 1000)
}

// 处理重试
const handleRetry = async () => {
  retrying.value = true
  try {
    await new Promise(resolve => setTimeout(resolve, 1000))
    emit('retry')
  } finally {
    retrying.value = false
  }
}

// 返回首页
const handleGoHome = () => {
  router.push('/main/dashboard')
  emit('goHome')
}

// 刷新页面
const handleRefresh = () => {
  window.location.reload()
}

onMounted(() => {
  window.addEventListener('online', handleOnline)
  window.addEventListener('offline', handleOffline)
  
  if (props.type === 'network' && !networkStatus.online && props.autoRetry) {
    startRetryCountdown()
  }
})

onUnmounted(() => {
  window.removeEventListener('online', handleOnline)
  window.removeEventListener('offline', handleOffline)
  if (retryTimer) {
    clearInterval(retryTimer)
  }
})
</script>

<style scoped>
.error-page {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 20px;
}

.error-container {
  text-align: center;
  max-width: 600px;
  width: 100%;
  background: white;
  border-radius: 16px;
  padding: 60px 40px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.1);
}

.error-icon {
  font-size: 80px;
  color: #f56c6c;
  margin-bottom: 30px;
}

.error-title {
  font-size: 28px;
  color: #303133;
  margin-bottom: 16px;
  font-weight: 600;
}

.error-description {
  font-size: 16px;
  color: #606266;
  margin-bottom: 30px;
  line-height: 1.6;
}

.network-status {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 30px;
  text-align: left;
}

.status-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.status-item:last-child {
  margin-bottom: 0;
}

.status-label {
  color: #909399;
  font-size: 14px;
}

.status-value {
  font-size: 14px;
  font-weight: 500;
}

.status-value.online {
  color: #67c23a;
}

.status-value.offline {
  color: #f56c6c;
}

.error-actions {
  display: flex;
  gap: 16px;
  justify-content: center;
  margin-bottom: 30px;
  flex-wrap: wrap;
}

.error-details {
  text-align: left;
}

.details-content {
  padding: 16px 0;
}

.detail-item {
  display: flex;
  margin-bottom: 12px;
}

.detail-item:last-child {
  margin-bottom: 0;
}

.detail-label {
  min-width: 80px;
  color: #909399;
  font-size: 14px;
}

.detail-value {
  color: #606266;
  font-size: 14px;
  word-break: break-all;
}

@media (max-width: 768px) {
  .error-container {
    padding: 40px 20px;
  }
  
  .error-icon {
    font-size: 60px;
  }
  
  .error-title {
    font-size: 24px;
  }
  
  .error-actions {
    flex-direction: column;
    align-items: center;
  }
  
  .error-actions .el-button {
    width: 100%;
    max-width: 200px;
  }
}
</style>
